//
//  DataBaseSImple.m
//  XMLDemo
//
//  Created by qianfeng on 15/1/4.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "DataBaseSImple.h"
#import "FMDB.h"
#import "YCHeroModel.h"

@implementation DataBaseSimple
{
    // 非线程安全 加锁
    // FMDatabase * _dataBase;
    
    // 线程安全
    FMDatabaseQueue * _dbQueue;
}

+(id)shareInstance
{
    static DataBaseSimple * simple = nil;
    
    static dispatch_once_t token;
    
    dispatch_once(&token, ^{
        simple = [[DataBaseSimple alloc] init];
    });
    return simple;
}

// 打开数据库 创建表
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSString * path = [NSHomeDirectory() stringByAppendingString:@"/Documents/lolbox.db"];
        NSLog(@"path is %@",path);
        
        // 数据库在该方法内部已经被打开
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:path];
        // 队列实现线程安全
        [_dbQueue inDatabase:^(FMDatabase *db) {
            //战斗力
            if (![db executeUpdate:@"create table if not exists persistable_z_d_l (pk integer primary key autoincrement,league_points integer,tier integer,good integer,rank integer,icon text,blocked integer,level integer,zucheng_1 text,server text,zdl integer,name text,sn text)"]) {
                NSLog(@"create zdl_table error!");
            }
            //收藏
            if (![db executeUpdate:@"create table if not exists persistable_fav (pk integer primary key autoincrement,naname text,title text,name text)"]) {
                NSLog(@"create fav_table error!");
            }
        }];
    }
    return self;
}

//插入战斗力信息
- (void)insertIntoDB:(YCPowerModel *)model
{
    NSInteger w = [model.normal[@"w"] integerValue];
    NSInteger lo = [model.normal[@"lo"] integerValue];
    CGFloat rate = (CGFloat)w / lo;
    NSString *str = [NSString stringWithFormat:@"匹配:(胜:%d,负:%d,胜率:%.2f)",w,lo,rate];
    NSLog(@"%@",str);
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        
        if (![db executeUpdate:@"insert into persistable_z_d_l (league_points,tier,good,rank,icon,blocked,level,zucheng_1,server,zdl,name,sn) values (?,?,?,?,?,?,?,?,?,?,?,?)",
              model.warzoneDict[@"league_points"],
              model.warzoneDict[@"tier"],
              model.global[@"good"],
              model.warzoneDict[@"rank"],
              model.global[@"icon"],
              model.global[@"blocked"],
              model.global[@"level"],
              str,
              model.zone,
              model.zdl[@"totalScore"],
              model.name,
              model.global[@"sn"]
              ])
        {
            NSLog(@"insert db error!");
        }
    }];
}

- (void)insertIntoDBWithHero:(YCHeroModel *)model withIsSuccess:(void (^)(BOOL isSuccess))success
{
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        
        if (![db executeUpdate:@"insert into persistable_fav (naname,title,name) values (?,?,?)",model.cnName,model.title,model.enName])
        {
            NSLog(@"insert db error!");
            success(NO);
        }
        else
        {
            success(YES);
        }
    }];
}

//删除
- (void)deleFromDBWithPower:(NSInteger)zdl
{
    NSString *sql = [NSString stringWithFormat:@"delete from persistable_z_d_l where zdl = %i",zdl];
    [_dbQueue inDatabase:^(FMDatabase *db) {
        if (![db executeUpdate:sql]) {
            NSLog(@"del error");
        }
    }];

}

- (void)deleFromDBWithHero:(NSString *)name withIsSuccess:(void (^)(BOOL isSuccess))success
{
    NSString *sql = [NSString stringWithFormat:@"delete from persistable_fav where name like '%@'",name];
    [_dbQueue inDatabase:^(FMDatabase *db) {
        if (![db executeUpdate:sql]) {
            NSLog(@"del error");
            success(NO);
        }
        else
        {
            success(YES);
        }
    }];
}

//查询
- (NSMutableArray *)selectFromDB
{
    // 在block中访问变量 添加变量修饰关键字__block
    __block NSMutableArray * arr = [NSMutableArray array];
    [_dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet * results = [db executeQuery:@"select * from persistable_z_d_l"];
        
        while ([results next]) {
            
            YCPowerModel *model = [[YCPowerModel alloc] init];
//            league_points,tier,good,rank,icon,blocked,level,zucheng_1,server,zdl,name,sn
            model.league_points = @([results intForColumn:@"league_points"]);
            model.tier = @([results intForColumn:@"tier"]);
            model.good = @([results intForColumn:@"good"]);
            model.rank = @([results intForColumn:@"rank"]);
            model.icon = [results stringForColumn:@"icon"];
            model.blocked = @([results intForColumn:@"blocked"]);
            model.level = @([results intForColumn:@"level"]);
            model.zucheng_1 = [results stringForColumn:@"zucheng_1"];
            model.server = [results stringForColumn:@"server"];
            model.zdlSorce = @([results intForColumn:@"zdl"]);
            model.name = [results stringForColumn:@"name"];
            model.sn = [results stringForColumn:@"sn"];
            
            [arr addObject:model];
        }
    }];
    return arr;
}

- (NSMutableArray *)selectFromDBWithHero:(NSString *)cnName
{
    NSString *sql = [NSString stringWithFormat:@"select * from persistable_fav"];
    __block NSMutableArray *arr = [NSMutableArray array];
    [_dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *results = [db executeQuery:sql];
        
        while ([results next]) {
            NSString *rel = [results stringForColumn:@"name"];
            
            if ([rel isEqualToString:cnName])
            {
                [arr addObject:rel];
            }
        }
    }];
    return arr;
}
- (NSMutableArray *)selectFromDBWithAllFavHero
{
    NSString *sql = [NSString stringWithFormat:@"select * from persistable_fav"];
    __block NSMutableArray *arr = [NSMutableArray array];
    [_dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *results = [db executeQuery:sql];
        
        while ([results next]) {
            YCHeroModel *mo = [[YCHeroModel alloc] init];
            mo.enName = [results stringForColumn:@"name"];
            mo.img = [results stringForColumn:@"name"];
            mo.title = [results stringForColumn:@"title"];
            mo.cnName = [results stringForColumn:@"naname"];
            [arr addObject:mo];
        }
    }];
    return arr;
}


@end
